<?php
require_once ("config.inc.php");
require_once ("utils.inc.php");
header ( "Content-Type: text/html; charset=utf-8" );
if (! isset ( $_FILES ["file"] ))
	die ( "Hello, world!" );
function getReturnData($succeeded, $msg = "failed", $url = "") {
	$ret = array (
			"succeeded" => ( int ) $succeeded,
			"msg" => $msg,
			"url" => $url 
	);
	return json_encode ( $ret );
}
if (isset ( $_SERVER ["HTTP_X_FORWARDED_FOR"] )) {
	if (isset ( $_SERVER ["HTTP_CLIENT_IP"] )) {
		$proxy = $_SERVER ["HTTP_CLIENT_IP"];
	} else {
		$proxy = $_SERVER ["REMOTE_ADDR"];
	}
	$ip = $_SERVER ["HTTP_X_FORWARDED_FOR"];
} 

else {
	if (isset ( $_SERVER ["HTTP_CLIENT_IP"] )) {
		$ip = $_SERVER ["HTTP_CLIENT_IP"];
	} else {
		$ip = $_SERVER ["REMOTE_ADDR"];
	}
}

$fileTypes = array (
		'jpg',
		'jpeg',
		'gif',
		'png' 
); // File extensions
$fileParts = pathinfo ( $_FILES ['file'] ['name'] );
$fext = strtolower ( $fileParts ['extension'] );

if (in_array ( $fext, $fileTypes )) {
	if ($_FILES ["file"] ["size"] <= MAXImgSize) {
		if ($_FILES ["file"] ["error"] > 0) {
			die ( getReturnData ( false, "Return Code: " . $_FILES ["file"] ["error"] ) );
		} else {
			$con = mysql_connect ( MySQLHost, MySQLUser, MySQLPass );
			if (! $con) {
				die ( getReturnData ( false, 'Could not connect: ' . mysql_error () ) );
			}
			mysql_select_db ( MySQLDB, $con );
			
			$sql = 'INSERT INTO `imglist` (' . ' `imgid` ,' . ' `ext` ,' . ' `uploadip` ,' . ' `uploaddate` ,' . ' `lastdate` ,' . ' `clicks` ,' . ' `exp` ,' . ' `bw`' . ' )' . ' VALUES (' . ' NULL , \'' . $fext . '\', \'' . $ip . '\', NOW( ) , NOW( ) , \'0\', NOW( ) , \'0\'' . ' );';
			$result = mysql_query ( $sql );
			if (! $result) {
				die ( getReturnData ( false, 'SQL Failed: ' . mysql_error () ) );
			}
			$result = encodeID ( mysql_insert_id () );
			// echo"Upload: ".$_FILES["file"]["name"]."<br />";
			// echo"Type: ".$_FILES["file"]["type"]."<br />";
			// echo"Size: ".($_FILES["file"]["size"] / 1024.0)." KB<br />";
			$storename = "upload/" . $result . ".bin";
			if (file_exists ( $storename ))
				unlink ( $storename );
			if (! move_uploaded_file ( $_FILES ["file"] ["tmp_name"], $storename )) {
				die ( getReturnData ( false, 'Failed to store uploaded file.' ) );
			}
			if (isset ( $_REQUEST ['noscript'] ))
				echo '<HTML><HEAD><meta http-equiv="refresh" content="0;url=result.php?imgid=' . $result . '&name=' . $_FILES ["file"] ["name"] . '&size=' . $_FILES ["file"] ["size"] . '&ext=' . $fext . '"></HEAD><BODY>Redirecting</BODY></HTML>';
			else
				echo getReturnData ( true, $_FILES ["file"] ["name"] . ' uploaded.', URLBase . 'd' . $result . '.' . $fext );
		}
	} 

	else
		die ( getReturnData ( false, 'File Too Large' ) );
} else
	die ( getReturnData ( false, 'Invalid File' ) );
?>